<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class user extends CI_Controller{	
	var $title = "Jogja Nuws";
	var $setting;
	var $cust_validation_msg = array(
		'alpha_dash'	=> 'Input harus berupa karakter, angka dan dash',
		'required'		=> '%s harus di isi',
		'matches'		=> '%s tidak cocok'
		);

	public function __construct(){
		parent::__construct();
		$this->load->helper('file');
		$this->load->model(array('user_model', 'post_model', 'kategori_model', 'log_model'));		
		$this->setting = $this->settings();
	}

	public function index(){
		redirect(site_url('user/post'));
	}

	#start post
	public function post($page_id=0){		
		$this->_validate_cookie();
		$data['title'] = $this->title;
		$data['desc'] = "Post";
		$data['page'] = 'post';
		$data['page_title'] = "Posts List";

		$data['category'] = $this->kategori_model->get_all();

		$page_query = $this->post_model->get_by_user(get_cookie('c_usr_id'));		

		$paginate_data = array(
			'page_id'		=> $page_id,
			'query'			=> $page_query,
			'base_url'		=> 'post',
			'uri_segment'	=> 3,
			'per_page'		=> $this->setting['user_pagination'],
			'num_links'		=> 3
			);
		$data['post'] = $this->post_paginator($paginate_data);

		$this->load->view('user/index', $data);
	}
	private function post_paginator($data){
		$this->load->library('pagination');
		$jml = $data['query'];
		//pengaturan pagination
		$config['base_url'] = site_url()."/user/".$data['base_url'];
		$config['uri_segment'] = $data['uri_segment'];
		$config['total_rows'] = count($jml);
		$config['per_page'] = $data['per_page'];
		$config['num_links'] = $data['num_links'];

		/*designing pagination*/
		$config['full_tag_open'] = "<span>";
		$config['full_tag_close'] = "</span>";
		$config['prev_link'] = '<i class="fa fa-backward"></i>';
		$config['prev_tag_open'] = "<span class='page_nav'>";
		$config['prev_tag_close'] = "</span>";
		$config['num_tag_open'] = "<span>";
		$config['num_tag_close'] = "</span>";
		$config['next_link'] = '<i class="fa fa-forward"></i>';
		$config['next_tag_open'] = "<span class='page_nav'>";
		$config['next_tag_close'] = "</span>";
		$config['cur_tag_open'] = "<span class='current'>";
		$config['cur_tag_close'] = "</span>";

		$this->pagination->initialize($config);
        //buat pagination
		$data['halaman'] = $this->pagination->create_links();
		$data['query'] = $this->post_model->post_by_user_paged($config['per_page'], $data['page_id']);
		$data['total'] = $config['total_rows'];

		return $data;
	}
	public function store_post(){
		$input = $this->input->post();
		if($input['btn_new_post'] != ""){
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('','');			
			$this->form_validation->set_message($this->cust_validation_msg);
			$rules = array(
				array(
					'field'	=> 'post_title',
					'label'	=> 'Judul',
					'rules'	=> 'required'
					),
				array(
					'field'	=> 'post_content',
					'label'	=> 'Konten',
					'rules'	=> 'required'
					)
				);	
			$this->form_validation->set_rules($rules);
			$this->load->library('upload');
			if($this->form_validation->run() == true){				
				$new_file_name = 'postimage-'.date('Ymd-his').rand(5,20);
				$config['upload_path'] = './asset/img/posts-image/';
				$config['allowed_types'] = 'gif|jpg|jpeg|png';
				$config['max_size']	= '2000';
				$config['max_width']  = '1500';
				$config['file_name'] = $new_file_name;	


				$this->upload->initialize($config);
				if ($this->upload->do_upload('post_foto')){
					$upload_msg = $this->upload->data();
					$input['foto'] =$upload_msg['file_name'];
					$input['permalink'] = $this->clean_permalink($input['post_title']);
					
					/* multi-category convertion */
					$cat_counter = $this->db->count_all('jonu_category');
					$cat_str = "";
					for($i=1; $i<=$cat_counter; $i++){
						if(isset($input["cat$i"])){
							$cat_str .= $input["cat$i"]." ";
						}
					}
					$cat_str = substr($cat_str, 0, strlen($cat_str)-1);
					$input['category'] = explode(" ", $cat_str);		
					/* end multi-category convertion */

					$do_store = $this->post_model->store($input);			

					if($do_store){
						$this->session->set_flashdata('notif_status', '1');
						$this->session->set_flashdata('notif', 'Tambah post berhasil');
					}else{
						$this->session->set_flashdata('notif_status', '0');
						$this->session->set_flashdata('notif', 'Tambah post gagal');
					}
					redirect(site_url('user/post'));
				}else{
					$this->session->set_flashdata('notif_status', '0');
					$this->session->set_flashdata('notif', 'Tambah post gagal');

					redirect(site_url('user/post'));
				}
			}else{
				$this->session->set_flashdata('notif_status', '0');
				$this->session->set_flashdata('notif', 'Tambah post gagal');

				redirect(site_url('user/post'));
			}			
		}else{
			redirect(site_url('user/post'));
		}
	}
	public function edit_post($post_id){
		$this->_validate_cookie();
		$data['title'] = $this->title;
		$data['desc'] = "Edit Post";
		$data['page'] = 'post_edit';
		$data['page_title'] = 'Edit Post';
		$data['post'] = $this->post_model->get_by_user(get_cookie('c_usr_id'));
		$data['category'] = $this->kategori_model->get_all();
		$data['post_edit'] = $this->post_model->get_by_id($post_id);

		$this->load->view('user/index', $data);
	}	
	public function update_post($id){
		$this->_validate_cookie();
		$input = $this->input->post();
		$image = $_FILES['photo'];
		if($input['adm_btn_post_edit'] != ""){
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('','');			
			$this->form_validation->set_message($this->cust_validation_msg);
			$rules = array(
				array(
					'field'	=> 'post_title',
					'label'	=> 'Judul Post',
					'rules'	=> 'required'
					),
				array(
					'field'	=> 'post_content',
					'label'	=> 'Konten',
					'rules'	=> 'required'
					)
				);
			$this->form_validation->set_rules($rules);
			if($this->form_validation->run() == true){
				#apakah file foto diganti?
				if($image['name'] != ""){ 
					$this->db->where('jonu_post_id', $id);
					$get_post = $this->db->get('jonu_post');
					$get_post_res = $get_post->result_array();
					$post_img_checker = $get_post_res[0]['jonu_post_image'];

					#apakah field jonu_post_image tidak kosong?
					if($post_img_checker != ""){
						$do_del_old_photo = unlink("./asset/img/posts-image/$input[curr_photo]");
						#apakah current photo berhasil dihapus?
						if($do_del_old_photo){
							$data = array('jonu_post_image' => '');
							$this->db->where('jonu_post_id', $id);
							#kosongkan field jonu_post_image
							$clear_img_dbrec = $this->db->update('jonu_post', $data); 	
						}
					}

					$this->load->library('upload');
					$new_file_name = 'postimage-'.date('Ymd-his').rand(5,20);
					$config['upload_path'] = './asset/img/posts-image/';
					$config['allowed_types'] = 'gif|jpg|jpeg|png';
					$config['max_size']	= '2000';
					$config['max_width']  = '1500';
					$config['file_name'] = $new_file_name;	


					$this->upload->initialize($config);
					if ($this->upload->do_upload('photo')){
						$upload_msg = $this->upload->data();
						$input['foto'] =$upload_msg['file_name'];
					}
				}

				$input['post_id'] = $id;

				$cat_counter = $this->db->count_all('jonu_category');
				$cat_str = "";
				for($i=1; $i<=$cat_counter; $i++){
					if(isset($input["cat_$i"])){
						$cat_str .= $input["cat_$i"]." ";
					}
				}
				$cat_str = substr($cat_str, 0, strlen($cat_str)-1);
				$input['category'] = explode(" ", $cat_str);		

				if($this->post_model->update_by_adm($input) == true){
					$this->session->set_flashdata('notif', 'Updating post success');
					$this->session->set_flashdata('notif_status', '1');
				}else{
					$this->session->set_flashdata('notif', 'Updating post fail');
					$this->session->set_flashdata('notif_status', '0');
				}
				redirect(site_url("user/edit_post/$id"));

			}else{
				$this->session->set_flashdata('notif', validation_errors());
				$this->session->set_flashdata('notif_status', '0');
				redirect(site_url("user/edit_post/$id"));
			}
		}else{
			redirect(site_url('user/post'));
		}	
	}
	public function destroy_post($id){
		if($this->post_model->destroy($id)){
			$this->session->set_flashdata('notif', 'Deleting post success');
			$this->session->set_flashdata('notif_status', '1');
		}else{
			$this->session->set_flashdata('notif', 'Deleting post fail');
			$this->session->set_flashdata('notif_status', '0');
		}
		redirect(site_url("mimin_jonu/post"));
	}
	#finish post

	#start pengaturan
	public function pengaturan(){
		$this->_validate_cookie();
		$data['title'] = $this->title;
		$data['desc'] = "User Dashboard";
		$data['page'] = 'usersetting';
		$data['page_title'] = "Setting";
		$data['category'] = $this->kategori_model->get_all();
		$data['user'] = $this->user_model->get_by_id(get_cookie('c_usr_id'));
		$this->load->view('user/index', $data);
	}
	public function update_setting(){
		$this->_validate_cookie();
		$input = $this->input->post();

		$rules = array(
			array(
				'field'	=> 'usr_fullname',
				'label'	=> 'Nama Lengkap',
				'rules'	=> 'required'
				),
			array(
				'field'	=> 'usr_email',
				'label'	=> 'Email',
				'rules'	=> 'required'
				),
			array(
				'field'	=> 'usr_jk',
				'label'	=> 'Jenis Kelamin',
				'rules'	=> 'required'
				)
			);

		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('','');	
		$this->form_validation->set_message($this->cust_validation_msg);
		$this->form_validation->set_rules($rules);	

		if($this->form_validation->run() == true){
			if($this->user_model->update_setting($input)){
				$this->_make_cookie('c_usr_fullname', $input['usr_fullname'], time()+3600);
				$this->session->set_flashdata('notif_status', '1');
				$this->session->set_flashdata('notif', 'Updating setting success');
			}else{
				$this->session->set_flashdata('notif_status', '0');
				$this->session->set_flashdata('notif', 'Updating setting fail');	
			}
			redirect(site_url('user/pengaturan'));
		}else{
			$this->session->set_flashdata('notif_status', '0');
			$this->session->set_flashdata('notif', 'Updating setting fail');
			redirect(site_url('user/pengaturan'));
		}
	}

	public function change_pass(){
		$this->_validate_cookie();
		$input = $this->input->post();
		if($input['btn_chg_pass'] != ""){
			$rules = array(
				array(
					'field'	=> 'old_pass',
					'label'	=> 'Password Lama',
					'rules'	=> 'required'
					),
				array(
					'field'	=> 'new_pass',
					'label'	=> 'Password Baru',
					'rules'	=> 'required'
					),
				array(
					'field'	=> 'retype_new_pass',
					'label'	=> 'Password Baru',
					'rules'	=> 'required|matches[new_pass]'
					)
				);
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('','');	
			$this->form_validation->set_message($this->cust_validation_msg);
			$this->form_validation->set_rules($rules);

			if($this->form_validation->run() == true){
				if($this->user_model->change_pass($input)){
					$this->session->set_flashdata('notif_status', '1');
					$this->session->set_flashdata('notif', 'Changing password success');
				}else{
					$this->session->set_flashdata('notif_status', '0');
					$this->session->set_flashdata('notif', 'Changing password fail');
				}
				redirect(site_url('user/pengaturan'));
			}else{
				$this->session->set_flashdata('notif_status', '0');
				$this->session->set_flashdata('notif', validation_errors());
				redirect(site_url('user'));
			}
		}else{
			$this->session->set_flashdata('notif_status', '0');
			$this->session->set_flashdata('notif', 'Changing password fail');
			redirect(site_url('user'));
		}		
	}

	public function update_pp(){
		$this->_validate_cookie();
		$input = $this->input->post();
		$foto = $_FILES['foto'];

		if($input['btn_usr_photo_upload'] != ""){
			if($foto['error'] == 0){
				$this->load->library('upload');
				$new_file_name = 'user-photo-'.date('Ymd-his').rand(5,20);
				$config['upload_path'] = './asset/img/auth-foto/';
				$config['allowed_types'] = 'gif|jpg|jpeg|png';
				$config['max_size']	= '2000';
				$config['max_width']  = '700';
				$config['file_name'] = $new_file_name;

				$this->upload->initialize($config);
				if ($this->upload->do_upload('foto')){
					$upload_msg = $this->upload->data();
					$input['foto'] =$upload_msg['file_name'];
					$foto_width = $upload_msg['image_width'];
					$foto_height = $upload_msg['image_height'];

					if($foto_width == $foto_height){
						if($this->user_model->update_pp($input['foto'])){
							$this->_make_cookie('c_usr_photo', $input['foto'], time()+3600);
							$this->session->set_flashdata('notif_status', '1');
							$this->session->set_flashdata('notif', 'Updating photo success');
						}else{
							$this->session->set_flashdata('notif_status', '0');
							$this->session->set_flashdata('notif', 'Updating photo fail');
						}
						redirect(site_url('user/pengaturan'));
					}else{
						unlink("./asset/img/auth-foto/$input[foto]");
						$this->session->set_flashdata('notif_status', '0');
						$this->session->set_flashdata('notif', 'Photo you uploaded was not square image');
						redirect(site_url('user/pengaturan'));
					}
				}else{
					$this->session->set_flashdata('notif_status', '0');
					$this->session->set_flashdata('notif', $this->upload->display_errors('<small style="font-size:12px">','</small>'));
					redirect(site_url('user/pengaturan'));
				}
			}else{
				$this->session->set_flashdata('notif_status', '0');
				$this->session->set_flashdata('notif', 'Select photo to be uploaded');
				redirect(site_url('user/pengaturan'));
			}
		}else{
			redirect(site_url('user/pengaturan'));
		}
	}

	public function login(){
		$data['title'] = $this->title;
		$data['desc'] = "Login User";

		$this->load->view('kholid_views/user/login', $data);
	}

	public function login_check(){
		$input = $this->input->post();
		if(!empty($input['btn_login_usr'])){			
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('','');			
			$rules = array(
				array(
					'field'	=> 'usr_username',
					'label'	=> 'Username',
					'rules'	=> 'required|alpha_dash'
					),
				array(
					'field'	=> 'usr_pass',
					'label'	=> 'Password',
					'rules'	=> 'required'
					)
				);
			$this->form_validation->set_rules($rules);

			if($this->form_validation->run() == true){
				$login_data = $this->user_model->login_check($input);
				if(count($login_data) > 0){
					# insert to login activity data
					$this->log_model->store($login_data[0]['jonu_user_id']);

					$this->_make_cookie('c_usr_id', $login_data[0]['jonu_user_id'], time()+3600);
					$this->_make_cookie('c_usr_usrname', $login_data[0]['jonu_user_username'], time()+3600);
					$this->_make_cookie('c_usr_fullname', $login_data[0]['jonu_user_fullname'], time()+3600);
					$this->_make_cookie('c_usr_photo', $login_data[0]['jonu_user_photo'], time()+3600);
					$this->_make_cookie('c_usr_status', $login_data[0]['jonu_user_status'], time()+3600);
					
					redirect(site_url());
				}else if($login_data == false){
					$this->session->set_flashdata('notif_status', '0');
					$this->session->set_flashdata('notif', 'Username atau password salah');
					redirect(site_url("/"));	
				}
			}else{
				$this->session->set_flashdata('notif_status', '0');
				$this->session->set_flashdata('notif', 'Login Gagal');
				redirect(site_url("/"));
			}
		}else{
			redirect(site_url('/'));
		}
	}

	public function logout(){
		$this->_delete_cookie("c_usr_id");
		$this->_delete_cookie("c_usr_usrname");
		$this->_delete_cookie("c_usr_fullname");
		$this->_delete_cookie("c_usr_photo");
		$this->_delete_cookie("c_usr_status");
		$this->session->set_flashdata('notif_status', '1');
		$this->session->set_flashdata('notif', 'Anda telah logout');

		redirect(site_url());
	}

	private function _validate_cookie(){
		if(get_cookie("c_usr_id") == "" || get_cookie("c_usr_usrname") == "" || get_cookie("c_usr_fullname") == "" || get_cookie("c_usr_status") == ""){
			redirect(site_url("/"));
		}else{
			if(get_cookie("c_usr_status") == "blocked" || get_cookie("c_usr_status") == "not verified"){
				redirect(site_url("/"));
			}
		}
	}
	private function _make_cookie($name, $value, $expire){
		set_cookie($name, $value, $expire);
	}
	private function _delete_cookie($name){
		delete_cookie($name);
	}
	private function clean_permalink($str){	
		$str = substr($str, 0,85);
		$str = strtolower($str);
		$str = preg_replace('/[^a-zA-Z0-9]/i',' ', $str);
		$str = trim($str);
		$str = preg_replace('/\s+/', ' ', $str);
		$str = preg_replace('/\s+/', '-', $str);

		return $str;
	}
	private function settings(){
		$this->load->model('settings_model');

		$q_per_page_setting = $this->settings_model->get_all();
		foreach($q_per_page_setting as $q_per_page_setting_rec){
			if($q_per_page_setting_rec['jonu_setting_id'] == "user_pagination"){
				$setting['user_pagination'] = $q_per_page_setting_rec['jonu_setting_value'];
			}
		}

		return $setting;
	}
}

/* End of file user.php */
/* Location: ./application/controllers/user.php */